<?php
/**
 * Created by Wang.
 * User: nango
 * Date: 2016-06-02
 * Time: 16:22
 */
namespace Wang\Database;

use mysqli;


class DbMysqli implements Database
{

    /**
     * @var $db 数据库实例对象
     */
    private $db;

    /**
     * @var $_instance 单例对象
     */
    static $_instance;

    /**
     * @var $_handle 数据库操作句柄
     */
    protected $_handle;

    /**
     * @var 受影响的行数
     */
    protected $_rows;

    /**
     * @var stmt
     */
    protected $stmt;



    function __construct($db = array())
    {
        //error_reporting(0);
        try {
            $this->db = new mysqli($db['host'], $db['username'], $db['password'], $db['dbname']);
            $this->db->query($db['charset']);//设置数据库编码
            if ($this->db->connect_errno) {
                die('mysqli 连接数据库失败' . $this->db->connect_error);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * @param $sql 查询语句
     * @return $this
     * 查询
     */
    function query($sql)
    {
        $this->_handle = $this->db->query($sql);
        return $this;
    }

    /**
     * @return array
     * 获取全部结果集
     */
    function fetchAll()
    {
        while ($row = $this->_handle->fetch_assoc()) {
            $data[] = $row;
        }
        //释放资源
        $this->_handle->free();
        return $data;
    }

    /**
     * @return int 返回受影响的行数
     */
    function affectRows()
    {
        return $this->_rows = $this->db->affected_rows;
    }

    /**
     * @return array 获取结果集中的第一列值
     */
    function fetchRow()
    {
        $row = $this->_handle->fetch_assoc();
        //释放资源
        $this->_handle->free();
        return $row;
    }

    /**
     * 预处理
     * @param $sql
     * @return array
     */
    function prepare($sql, $params)
    {
        $this->stmt =  $this->db->stmt_init();
        $this->stmt = $this->db->prepare($sql);
        $this->stmt->bind_param("s", $params);

        $this->stmt->execute();

        $this->stmt->bind_result($result);

        $this->stmt->fetch();

        return $result;
    }

    /**
     * 执行预处理sql语句
     * @param $params
     * @return mixed
     */
    function execute($params){

    }

    /**
     * 获取单例
     */
    static function getInstance($config)
    {
        if (!self::$_instance) {
            self::$_instance = new self($config);
        }

        return self::$_instance;
    }
}